package com.building.hcrm.ui;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.building.hcrm.R;
import com.building.hcrm.base.BaseActivity;
import com.building.hcrm.base.BaseAsyncTask;
import com.building.hcrm.base.BaseStaffSelector.SelectedStaffListener;
import com.building.hcrm.common.ComConst;
import com.building.hcrm.common.ComFunc;
import com.building.hcrm.common.User;
import com.building.hcrm.common.Utils;
import com.building.hcrm.model.PlanDetail;
import com.building.hcrm.model.PlanExamine;
import com.building.hcrm.model.SysUser;
import com.building.hcrm.ui.customcontrols.ComStaffSelector;
import com.building.hcrm.wcf.TaskServiceProxy;

public class TaskStatusChangeActivity extends BaseActivity
{
	private EditText _txtTaskContent;
	private EditText _txtTaskAdvise;
	private LinearLayout _lyAction;
	private Button _btnAction0;
	private Button _btnAction1;
	private Button _btnAction2;
	private ComStaffSelector _selector;

	private Button _btnDateFrom;
	private Button _btnDateTo;
	private ImageButton _imgBtnRe;
	private TextView _txtTitle;
	private ImageButton _imgBtnTitleRight;
	
	private PlanDetail _model;

	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		// TODO 自动生成的方法存根
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_task_status_change);
//		if (android.os.Build.VERSION.SDK_INT > 9) {
//		    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
//		    StrictMode.setThreadPolicy(policy);
//		}
		InitTitle();
		_selector = (ComStaffSelector) findViewById(R.id.staff_selector);
		Serializable data = getIntent().getSerializableExtra(
				ComConst.INTENT_EXTRA_SYSUSER);
		if (data != null) {
			_selector.load(ComStaffSelector.DISPLAY_TYPE_ALL, (SysUser)data);
		} else {
			_selector.load(ComStaffSelector.DISPLAY_TYPE_ALL, User.getInstance(this));
		}
		_model = (PlanDetail)getIntent().getSerializableExtra("PlanIns");
		FromToTimer(_model.PlanStartTime, _model.PlanEndTime);
		_txtTaskContent = (EditText)findViewById(R.id.txt_task_content);
		_txtTaskContent.setText(_model.PlanContent);
		_txtTaskAdvise = (EditText)findViewById(R.id.txt_task_advise);
		_txtTaskAdvise.setText(_model.PlanAdvise);
		_lyAction = (LinearLayout) findViewById(R.id.lay_task_action);
		_btnAction0 = (Button) findViewById(R.id.btn_task_action_0);
		_btnAction0.setOnClickListener(ActionClickListener);
		_btnAction1 = (Button) findViewById(R.id.btn_task_action_1);
		_btnAction1.setOnClickListener(ActionClickListener);
		_btnAction2 = (Button) findViewById(R.id.btn_task_action_2);
		_btnAction2.setOnClickListener(ActionClickListener);
		_selector.setOnSelectedStaffListener(selectedStaffListener);
	}
	
	private void SetBottonStateText() throws Exception
	{
		if(User.getInstance(getApplicationContext()).getUserNum().equals(_model.UserNumDo))
		{
			_txtTaskAdvise.setVisibility(View.GONE);
			if(getString(R.string.task_status_0).equals(_model.PlanState))
			{
				_btnAction0.setText(R.string.task_action_0);
				_btnAction1.setVisibility(View.GONE);
				_btnAction2.setVisibility(View.GONE);
			}
			else if(getString(R.string.task_status_1).equals(_model.PlanState))
			{
				_btnAction0.setText(R.string.task_action_1);
				_btnAction1.setText(R.string.task_action_2);
				_btnAction2.setText(R.string.task_action_3);
			}
			else if(getString(R.string.task_status_2).equals(_model.PlanState))
			{
				_btnAction0.setText(R.string.task_action_1);
				_btnAction1.setText(R.string.task_action_2);
				_btnAction2.setText(R.string.task_action_3);
			}
			else if(getString(R.string.task_status_3).equals(_model.PlanState))
			{
				_btnAction0.setText(R.string.task_action_1);
				_btnAction1.setText(R.string.task_action_2);
				_btnAction2.setText(R.string.task_action_3);
			}
//			else if(getString(R.string.task_status_4).equals(_model.PlanState))
//			{
//				_btnAction0.setText(R.string.task_action_1);
//				_btnAction1.setText(R.string.task_action_2);
//				_btnAction2.setText(R.string.task_action_3);
//			}
			else
			{
				_lyAction.setVisibility(View.GONE);
			}
		}
		else
		{
			_txtTaskAdvise.setVisibility(View.VISIBLE);
			_txtTaskAdvise.setEnabled(true);
			if(getString(R.string.task_status_4).equals(_model.PlanState) || (new Date()).after(_model.PlanEndTime))
			{
				_btnAction0.setText(R.string.task_action_4);
				_btnAction1.setText(R.string.task_action_5);
				_btnAction2.setText(R.string.task_action_6);
			}
			else
			{
				_lyAction.setVisibility(View.GONE);
			}
		}
	}

	private void InitTitle()
	{
		_imgBtnRe = (ImageButton) findViewById(R.id.imgbtn_home);
		_imgBtnRe.setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				finish();
			}
		});
		_txtTitle = (TextView) findViewById(R.id.titlePageName);
		_txtTitle.setText(R.string.task_status_change_title);
		_imgBtnTitleRight = (ImageButton) findViewById(R.id.imgbtn_save);
		_imgBtnTitleRight.setVisibility(View.INVISIBLE);
	}

	private void FromToTimer(Date dtFrom, Date dtTo)
	{
		try
		{
			Calendar calendar = Calendar.getInstance();
			SimpleDateFormat sdfdate;

			_btnDateFrom = (Button) findViewById(R.id.btn_date_selector_from);
			_btnDateFrom.setEnabled(false);
			_btnDateFrom.setOnClickListener(DatePickerButtion_Click);
			sdfdate = new SimpleDateFormat(ComConst.DATE_FORMAT, Locale.getDefault());
			_btnDateFrom.setText(sdfdate.format(dtFrom == null ? calendar.getTime() : dtFrom));

			_btnDateTo = (Button) findViewById(R.id.btn_date_selector_to);
			_btnDateTo.setEnabled(false);
			_btnDateTo.setOnClickListener(DatePickerButtion_Click);
			sdfdate = new SimpleDateFormat(ComConst.DATE_FORMAT, Locale.getDefault());
			_btnDateTo.setText(sdfdate.format(dtTo == null ? calendar.getTime() : dtTo));
		}
		catch (Exception e)
		{
			Log.e(LTAG, ComFunc.getExceptionMessage(e), e);
		}
	}

	private SelectedStaffListener selectedStaffListener = new SelectedStaffListener()
	{
		@Override
		public void onSelectedStaff(SysUser inStaff)
		{
			if (null != inStaff)
			{
				try
				{
					SetBottonStateText();
				}
				catch (Exception e)
				{
					Log.e(LTAG,ComFunc.getExceptionMessage(e),e);
				}
			}
		}
	};
	
	// 日期选择事件监听：OnClickListener
	private View.OnClickListener DatePickerButtion_Click = new View.OnClickListener()
	{
		@Override
		public void onClick(View v)
		{
			try
			{
				if (Utils.isFastDoubleClick())
					return;
				final Button button = (Button) v;

				// 日期設定
				Calendar calendar = Calendar.getInstance();
				int year = calendar.get(Calendar.YEAR);
				int monthOfYear = calendar.get(Calendar.MONTH);
				int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
				if (button.getText().length() > 0)
				{
					year = Integer.parseInt(button.getText().toString().split(ComConst.DATE_SEPARATOR)[0]);
					monthOfYear = Integer.parseInt(button.getText().toString().split(ComConst.DATE_SEPARATOR)[1]) - 1;
					dayOfMonth = Integer.parseInt(button.getText().toString().split(ComConst.DATE_SEPARATOR)[2]);
				}

				// 日付選択ﾀﾞｲｱﾛｸﾞ：OnDateSetListener
				DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener()
				{
					private int _year, _monthOfYear, _dayOfMonth;

					@Override
					public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
					{
						try
						{
							if (_year != year || _monthOfYear != monthOfYear || _dayOfMonth != dayOfMonth)
							{
								_year = year;
								_monthOfYear = monthOfYear;
								_dayOfMonth = dayOfMonth;
								Calendar calendar = Calendar.getInstance();
								calendar.set(year, monthOfYear, dayOfMonth);
								SimpleDateFormat sdf = new SimpleDateFormat(ComConst.DATE_FORMAT, Locale.getDefault());
								Date dtCheck = new Date(sdf.format(calendar.getTime()));
								if (CheckDateValue(button, dtCheck))
								{
									button.setText(sdf.format(calendar.getTime()));
									// DataBind();
								}
							}
						}
						catch (Exception e)
						{
							Log.e(LTAG, ComFunc.getExceptionMessage(e), e);
						}
					}

				};

				// 日付選択ﾀﾞｲｱﾛｸﾞ作成＆表示
				DatePickerDialog datePickerDialog = new DatePickerDialog(v.getContext(), dateSetListener, year,
						monthOfYear, dayOfMonth);
				datePickerDialog.show();
			}
			catch (Exception e)
			{
				Log.e(LTAG, ComFunc.getExceptionMessage(e), e);
			}
		}
	};

	private boolean CheckDateValue(Button button, Date checkDate)
	{
		Date compareDate = null;
		String alarmText = null;

		// 触发控件为起始时间
		if (button.getId() == _btnDateFrom.getId())
		{
			compareDate = new Date(_btnDateTo.getText().toString());
			if (checkDate.after(compareDate))
			{
				alarmText = "起始时间必须小于或等于结束时间";
				Toast.makeText(TaskStatusChangeActivity.this, alarmText, Toast.LENGTH_SHORT).show();
				return false;
			}
		}
		else if (button.getId() == _btnDateTo.getId())
		{
			compareDate = new Date(_btnDateFrom.getText().toString());
			if (checkDate.before(compareDate))
			{
				alarmText = "结束时间必须大于或等于起始时间";
				Toast.makeText(TaskStatusChangeActivity.this, alarmText, Toast.LENGTH_SHORT).show();
				return false;
			}
		}

		return true;
	}

	private View.OnClickListener ActionClickListener = new View.OnClickListener()
	{
		@Override
		public void onClick(View v)
		{
			Button btnV  = (Button)v;
			String str =null;
			if(getString(R.string.task_action_0).equals(btnV.getText()))
			{
				str=getString(R.string.task_status_1);
			}
			else if(getString(R.string.task_action_1).equals(btnV.getText()))
			{
				str=getString(R.string.task_status_2);
			}
			else if(getString(R.string.task_action_2).equals(btnV.getText()))
			{
				str=getString(R.string.task_status_3);
			}
			else if(getString(R.string.task_action_3).equals(btnV.getText()))
			{
				str=getString(R.string.task_status_4);
			}
			else if(getString(R.string.task_action_4).equals(btnV.getText()))
			{
				str=getString(R.string.task_status_5);
			}
			else if(getString(R.string.task_action_5).equals(btnV.getText()))
			{
				str=getString(R.string.task_status_6);
			}
			else if(getString(R.string.task_action_6).equals(btnV.getText()))
			{
				str=getString(R.string.task_status_7);
			}
			if(null != str)
				SaveAction(str);
		}
	};

	private void SaveAction(final String strState)
	{
		PlanExamine saveModel = new PlanExamine();
		saveModel.PlanID = _model.PlanID;
		saveModel.PlanState=strState;
		saveModel.PlanAdvise = _txtTaskAdvise.getText().toString();
		
		new BaseAsyncTask<PlanExamine, Object, Boolean>(TaskStatusChangeActivity.this,"提交...")
		{
			@Override
			protected void onPreExecute()
			{
				super.onPreExecute();
			}

			@Override
			protected Boolean doInBackground(PlanExamine... params)
			{
				Boolean re = false;
				if(null != params && params.length > 0)
				{
					try
					{
						re = TaskServiceProxy.getInstance(TaskStatusChangeActivity.this).TaskChangeState(params[0]);
					}
					catch (Exception e)
					{
						Log.e(LTAG,ComFunc.getExceptionMessage(e),e);
					}
				}
				return re;
			}

			@Override
			protected void onPostExecute(Boolean result)
			{
				super.onPostExecute(result);
				if(result)
				{
					Toast.makeText(TaskStatusChangeActivity.this,"提交成功！",Toast.LENGTH_SHORT).show();
					finish();
				}
				else
				{
					Toast.makeText(TaskStatusChangeActivity.this,"提交失败！",Toast.LENGTH_SHORT).show();
				}
			}
		}.execute(saveModel);
	}
}
